package com.digitalbuana.smiles.ui.helper;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;

import com.digitalbuana.smiles.R;
import com.digitalbuana.smiles.data.AppConstants;
import com.digitalbuana.smiles.dialog.SmilesProgressDialog;

import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.AnimationDrawable;
import android.os.AsyncTask;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;

public class ConnectionActivity extends Activity {

	
	
	protected String urlKu = "";
	protected String loadingMessage = "";
	protected List<NameValuePair> postData;
	protected boolean isAsyncLoading = false;
	private SmilesProgressDialog dialog;
	protected void doPostAsync(Context context, String url,  List<NameValuePair> postDatanya, String loadingTxt)
	{
		dialog = new SmilesProgressDialog(context, loadingTxt);
		dialog.show();
		isAsyncLoading = true;
		postData = postDatanya;
		urlKu = url;
		if(url!=null){
			new APISmilesAsync().execute(urlKu);
		}
	}
	
	protected void finishAsync(String result){
		isAsyncLoading = false;
		if(dialog!=null){
			dialog.dismiss();
		}
	}
	
	private class APISmilesAsync extends AsyncTask<String, Void, String>{
		@Override
		protected String doInBackground(String... params) {
			Log.e(AppConstants.TAG, "Post To : "+urlKu);
			urlKu = params[0];
			HttpClient httpclient = new DefaultHttpClient();
		    HttpPost httppost = new HttpPost(urlKu);
		    BufferedReader inStream = null;
		    try {
		    	if(postData!=null){
					httppost.setEntity(new UrlEncodedFormEntity(postData));
		    	}
				// Execute HTTP Post Request
		        HttpResponse response = httpclient.execute(httppost);
		        inStream = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
		        StringBuffer buffer = new StringBuffer("");
		        String line = "";
		        String NL = System.getProperty("line.separator");
		        while ((line = inStream.readLine()) != null) {
					buffer.append(line + NL);
				}
		        inStream.close();
		        String result = buffer.toString();
		        return result;
			} catch (Exception e) {
				finishAsync("");
				Log.e(AppConstants.TAG,"PostError : "+e.getMessage());
				return "";
			}
		}
		
		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			finishAsync(result);
		}
	}
	
}
